const Post = require('../models/Post');
const File = require('../models/File');
const User = require('../models/User'); // 新增：引入User模型

// 文件上传
exports.uploadFile = async (req, res) => {
    if (!req.file) {
        return res.status(400).json({ message: '文件上传失败' });
    }

    try {
        // 检查文件大小是否超过50MB
        if (req.file.size > 50 * 1024 * 1024) {
            return res.status(400).json({ message: '文件太大，请上传小于50MB的文件' });
        }

        // 将文件数据分块处理，避免超出缓冲区范围
        const fileChunks = [];
        const chunkSize = 1024 * 1024; // 1MB
        for (let i = 0; i < req.file.buffer.length; i += chunkSize) {
            fileChunks.push(req.file.buffer.slice(i, i + chunkSize));
        }

        const newFile = await File.create({
            filename: req.file.originalname,
            data: fileChunks, // 将文件数据存储为分块数组
            mimetype: req.file.mimetype,
            size: req.file.size,
            uploadedBy: req.user.id
        });

        res.status(200).json({
            message: '文件上传成功',
            file: newFile
        });
    } catch (error) {
        console.error('文件上传失败:', error);
        res.status(500).json({ message: '文件上传失败，请稍后重试' });
    }
};

// 发布帖子
exports.publishPost = async (req, res) => {
    const { title, content, category, mediaType, tags } = req.body;
    if (!title || !content || !category) {
        return res.status(400).json({ message: '标题、内容、分类不能为空' });
    }
    let cover = '';
    let fileId = null;
    // 处理图片上传（优先使用上传的图片）
    if (req.files && req.files.image && req.files.image[0]) {
        const img = req.files.image[0];
        const mime = img.mimetype;
        const base64 = img.buffer.toString('base64');
        cover = `data:${mime};base64,${base64}`;
    } else if (req.body.cover) {
        cover = req.body.cover;
    }
    // 处理文档附件
    if (req.files && req.files.file && req.files.file[0]) {
        const doc = req.files.file[0];
        // 存入File表
        const newFile = await File.create({
            filename: doc.originalname,
            data: doc.buffer,
            mimetype: doc.mimetype,
            size: doc.size,
            uploadedBy: req.user.id
        });
        fileId = newFile._id;
    }
    let tagsArr = [];
    if (typeof tags === 'string') {
        try {
            tagsArr = JSON.parse(tags);
        } catch {
            tagsArr = [];
        }
    } else if (Array.isArray(tags)) {
        tagsArr = tags;
    }
    try {
        const newPost = await Post.create({
            title,
            content,
            category,
            cover,
            mediaType: mediaType || 'image',
            tags: tagsArr,
            author: req.user.id,
            file: fileId
        });
        res.status(201).json({ message: '发布成功', data: newPost });
    } catch (error) {
        console.error('发布失败:', error);
        res.status(500).json({ message: '发布失败，请稍后重试' });
    }
};

// 获取帖子列表
exports.getPosts = async (req, res) => {
    try {
        const filter = req.query.category ? { category: req.query.category } : {};
        const posts = await Post.find(filter)
            .sort({ createdAt: -1 })
            .populate('author', 'nickname avatar');
        res.status(200).json(posts);
    } catch (error) {
        console.error('获取发布内容失败:', error);
        res.status(500).json({ message: '获取发布内容失败，请稍后重试' });
    }
};

// 分页+搜索获取帖子列表
exports.getPostsPaged = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const pageSize = parseInt(req.query.pageSize) || 30;
        const category = req.query.category;
        const search = req.query.search;
        const filter = {};
        if (category && category !== 'all') filter.category = category;
        if (search) {
            const regex = new RegExp(search, 'i');
            filter.$or = [
                { title: regex },
                { content: regex },
                { tags: regex }
            ];
        }
        const total = await Post.countDocuments(filter);
        const posts = await Post.find(filter)
            .sort({ createdAt: -1 })
            .skip((page - 1) * pageSize)
            .limit(pageSize)
            .populate('author', 'nickname avatar');
        res.status(200).json({
            total,
            page,
            pageSize,
            posts
        });
    } catch (error) {
        console.error('分页获取发布内容失败:', error);
        res.status(500).json({ message: '获取发布内容失败，请稍后重试' });
    }
};

// 删除帖子
exports.deletePost = async (req, res) => {
    try {
        const post = await Post.findById(req.params.id);
        if (!post) {
            return res.status(404).json({ message: '帖子不存在' });
        }

        // 检查当前用户是否为帖子的作者或管理员
        const user = await User.findById(req.user.id);
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }

        // 确保两者都是字符串类型进行比较
        if (post.author.toString() !== req.user.id.toString() && user.role !== 'admin') {
            return res.status(403).json({ message: '无权删除此帖子' });
        }

        await Post.findByIdAndDelete(req.params.id);
        res.status(200).json({ message: '帖子已删除' });
    } catch (error) {
        console.error('删除帖子失败:', error);
        res.status(500).json({ message: '删除帖子失败，请稍后重试' });
    }
};

// 获取单个帖子详情
exports.getById = async (req, res) => {
    try {
        const post = await Post.findById(req.params.id)
            .populate('author', 'nickname avatar');
            
        if (!post) {
            return res.status(404).json({ message: '帖子不存在' });
        }

        // 如果用户已登录，检查是否已点赞
        let isLiked = false;
        if (req.user) {
            isLiked = post.likedBy.includes(req.user.id);
        }

        // 更新浏览量
        post.views += 1;
        await post.save();

        res.status(200).json({
            code: 200,
            data: {
                ...post.toObject(),
                isLiked
            }
        });
    } catch (error) {
        console.error('获取帖子详情失败:', error);
        res.status(500).json({ message: '获取帖子详情失败，请稍后重试' });
    }
};

// 点赞/取消点赞帖子
exports.toggleLike = async (req, res) => {
    try {
        const postId = req.params.id;
        const userId = req.user.id;

        const post = await Post.findById(postId);
        if (!post) {
            return res.status(404).json({ message: '帖子不存在' });
        }

        const userLikedIndex = post.likedBy.indexOf(userId);
        if (userLikedIndex === -1) {
            // 点赞
            post.likedBy.push(userId);
            post.likes += 1;
        } else {
            // 取消点赞
            post.likedBy.splice(userLikedIndex, 1);
            post.likes = Math.max(0, post.likes - 1);
        }

        await post.save();

        res.json({
            code: 200,
            data: {
                likes: post.likes,
                isLiked: userLikedIndex === -1
            },
            message: userLikedIndex === -1 ? '点赞成功' : '已取消点赞'
        });
    } catch (error) {
        console.error('点赞操作失败:', error);
        res.status(500).json({ message: '操作失败，请稍后重试' });
    }
};
